import { Empty, Message, Table } from '@arco-design/web-react';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import DetailModal from '../../../components/detailModal';
import LoadingMask from '../../../components/loadingMask';
import { dictTag, keepCopy } from '../../../components/tableColumn';
import main from '../../../main';
import { getDict } from '../../../utils/utils';
import { apiGetCardPackOrderDetailList } from './api';
import { CardPackOrderDetail } from './types';
interface Props {
  cardId: number;
  onCancel: () => void;
}

const CARD_PACK_ORDER_DETAIL_STATUS = 'card_pack_order_detail_status';
const CARD_PACK_DETAIL_PACKAGE_TYPE = 'card_pack_detail_package_type';
export default function CardPackOrderDetailDialog({ cardId, onCancel }: Props) {
  const [list, setList] = useState<CardPackOrderDetail[]>([]);
  const [total, setTotal] = useState(1);
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(main.defaultPageSize);
  const [dictDatas, setDictDatas] = useState<Record<string, any>>({});
  useEffect(() => {
    async function fetchDictData() {
      const data = await getDict(CARD_PACK_DETAIL_PACKAGE_TYPE, CARD_PACK_ORDER_DETAIL_STATUS);
      setDictDatas(data);
    }
    fetchDictData();
  }, []); //eslint-disable-line

  useEffect(() => {
    loadList();
  }, [pageNum, pageSize]); // eslint-disable-line

  async function loadList() {
    LoadingMask.show();
    try {
      let res = await apiGetCardPackOrderDetailList(pageNum, pageSize, {
        cardId,
        orderByColumn: 'orderId,thisPhases',
        isAsc: 'desc',
      });
      let data = res.data;
      if (data.code === 200) {
        setList(data.rows ?? []);
        setTotal(data.total);
      } else {
        Message.warning(data.msg ?? '获取失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '获取失败');
    } finally {
      LoadingMask.hide();
    }
  }
  /**
   * 分页器 切换分页和条数
   * @param page 当前页数
   * @param size 每页条数
   */
  function handlePageAndSizeChange(page: number, size: number) {
    if (page === pageNum && size === pageSize) return;
    setPageSize(size);
    setPageNum(page);
  }

  let dataSource = (list || []).map((item: CardPackOrderDetail) => Object.assign({}, item, { key: item.id }));

  // 定义类型表格内的列
  const dataColumns = [
    {
      title: '充值卡号',
      dataIndex: 'iccid',
      key: 'iccid',
      width:120,
      render: keepCopy,
      fixed: 'left' as const
    },
    {
      title: '套餐包名',
      dataIndex: 'packName',
      width:120,
      key: 'packName',
    },
    {
      title: '套餐名称',
      dataIndex: 'packDetailName',
      width:120,
      key: 'packDetailName',
    },
    {
      title: '套餐类型',
      dataIndex: 'packageType',
      width:100,
      key: 'packageType',
      render: (v: string) => dictTag(v, dictDatas[CARD_PACK_DETAIL_PACKAGE_TYPE]),
    },
    {
      title: '总期数',
      dataIndex: 'totalPhases',
      key: 'totalPhases',
      width:100,
    },
    {
      title: '当前期数',
      dataIndex: 'thisPhases',
      key: 'thisPhases',
      width:100,
    },
    {
      title: '套餐金额',
      dataIndex: 'salePrice',
      key: 'salePrice',
      width:100,
    },
    {
      title: '订单金额',
      dataIndex: 'orderPrice',
      key: 'orderPrice',
      width:100,
    },
    {
      title: '实付金额',
      dataIndex: 'realPrice',
      key: 'realPrice',
      width:100,
    },
    {
      title: '优惠金额',
      dataIndex: 'couponPrice',
      key: 'couponPrice',
      width:100,
    },
    {
      title: '购买时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width:180,
    },
    {
      title: '生效时间',
      dataIndex: 'startEffectTime',
      key: 'startEffectTime',
      width:160,
      render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '结算时间',
      dataIndex: 'endEffectTime',
      width:160,
      key: 'endEffectTime',
      render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width:160,
      render: (v: string) => dictTag(v, dictDatas[CARD_PACK_ORDER_DETAIL_STATUS]),
      fixed: 'right' as const
    },
  ];
  return (
    <DetailModal
      title="订购记录"
      show
      cancelBtnShow={false}
      onConfirm={onCancel}
      onCancel={onCancel}
      className="bw-90"
      contentClassName="h-500"
    >
      <Table
        className="bw-100"
        data={dataSource}
        columns={dataColumns}
        scroll={{ x: 1000 }}
        pagination={{
          className: 'pagination-block',
          total: total || 1,
          current: pageNum,
          pageSize: pageSize,
          showJumper: true,
          sizeCanChange: true,
          sizeOptions: main.defaultPageSizeOptions,
          showTotal: (total) => `共${total}条`,
          size: 'small',
          onChange: handlePageAndSizeChange,
        }}
        noDataElement={<Empty description="暂无数据" />}
      />
    </DetailModal>
  );
}
